package com.agent.web;

import com.agent.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.agent.service.UserService;
import com.agent.dto.LoginRequestDTO;
import com.agent.dto.RegisterRequestDTO;
import com.agent.dto.UpdateUserRequestDTO;
import com.agent.entity.User;

import java.util.HashMap;
import java.util.Map;

@RestController("webUserController")
@RequiredArgsConstructor
@RequestMapping("/web/user")
public class UserController {

    private final UserService userService;

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequestDTO req) {
        Map<String, Object> resp = new HashMap<>();
        try {
            String token = userService.login(req);
            resp.put("code", 0);
            resp.put("msg", "ok");
            resp.put("token", token);
            return ResponseEntity.ok(resp);
        } catch (IllegalArgumentException e) {
            resp.put("code", 400);
            resp.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(resp);
        }
    }

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequestDTO req) {
        Map<String, Object> resp = new HashMap<>();
        try {
            Long userId = userService.register(req);
            resp.put("code", 0);
            resp.put("msg", "ok");
            resp.put("userId", userId);
            return ResponseEntity.ok(resp);
        } catch (IllegalArgumentException e) {
            resp.put("code", 400);
            resp.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(resp);
        }
    }

    // 用户登出

    // 用户信息
    @GetMapping("/info")
    public ResponseEntity<?> info(@RequestParam("id") Long id) {
        Map<String, Object> resp = new HashMap<>();
        User user = userService.getUserInfo(id);
        if (user == null) {
            resp.put("code", 404);
            resp.put("msg", "User not found");
            return ResponseEntity.status(404).body(resp);
        }
        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", user);
        return ResponseEntity.ok(resp);
    }

    // 用户修改
    @PutMapping("/update")
    public ResponseEntity<?> update(@RequestBody UpdateUserRequestDTO req) {
        Map<String, Object> resp = new HashMap<>();
        Long currentUserId = UserContext.getUserId();
        try {
            boolean ok = userService.updateUser(currentUserId, req);
            resp.put("code", 0);
            resp.put("msg", ok ? "ok" : "no change");
            return ResponseEntity.ok(resp);
        } catch (IllegalArgumentException e) {
            resp.put("code", 400);
            resp.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(resp);
        }
    }



}
